﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Simhopp.Model
{
    class Client : InterfaceClientModel
    {
        public string ID { get; private set; }
        public IPEndPoint EndPoint { get; private set; }

        Socket sck;

        public Client(Socket accepted)
        {
            sck = accepted;
            ID = Guid.NewGuid().ToString();
            EndPoint = (IPEndPoint)sck.RemoteEndPoint;
            sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
        }

        public void callback(IAsyncResult ar)
        {
            try
            {
                sck.EndReceive(ar);
                byte[] buf = new byte[1024];
                int rec = sck.Receive(buf, buf.Length, 0);

                if (rec < buf.Length)
                {
                    Array.Resize<byte>(ref buf, rec);
                }

                if (Recived != null)
                {
                    Recived(this, buf);
                }

                if(rec <= 1)
                {
                    Close();
                    if (Disconnected != null)
                    {
                        Disconnected(this);
                    }
                }

                sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);

            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Close();

                if (Disconnected != null)
                {
                    Disconnected(this);
                }
            }      
        }

        public void Close()
        {
            sck.Close();
            sck.Dispose();
            
        }

        public delegate void ClientRecivedHandler(Client sender, byte[] data);
        public delegate void ClientDisconnectHandler(Client sender);

        public event ClientRecivedHandler Recived;
        public event ClientDisconnectHandler Disconnected;
    }
}
